package com.xiia.dao;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import com.xiia.util.CheckConstant;
import com.xiia.util.DBConnect;
import com.xiia.util.Pager;
import com.xiia.vo.Rule;
import com.xiia.vo.RuleSort;
/**
 *  
 * @author 胡天天  2014-11-4
 * 政策法规dao
 *
 */
public class RuleDao extends BaseDao{
	private static RuleSortDao ruleSortDao;
	private static UserDao userDao;
	private static RuleSort ruleSort;
	private static QueryRunner query;
	public RuleDao(){
		ruleSortDao = new RuleSortDao();
		userDao = new UserDao();
		ruleSort = new RuleSort();
		query = new QueryRunner();
	}
	/**
	 * 添加政策法规
	 * 用事务实现对rulesort的该rulesortnum+1
	 * @param rule
	 * @return boolean
	 */
	@SuppressWarnings({ "deprecation", "unchecked", "rawtypes" })
	public boolean addRules(Rule rule){
		try {
			String sql = "insert into t_rule(title,link,addTime,status,sortId,userId)"+
					"values(?,?,?,?,?,?)";
			Object[] param = {rule.getTitle(),
							   rule.getLink(),new Date(),
							   CheckConstant.STATUS_WRITE_DONE,
							   rule.getRuleSort().getSortId(),
							   rule.getUser().getUserId()};
			conn = DBConnect.getConnect();
			conn.setAutoCommit(false);
			query.update(conn, sql, param);
			//通过sortId在t_rule_sort表中获得整个rulesort
			sql = "select * from t_rule_sort where sortId=?";
			Object[] param2 = {rule.getRuleSort().getSortId()};
			ruleSort = (RuleSort)query.query
					   (conn, sql, param2,new BeanHandler(RuleSort.class));
			sql = "update t_rule_sort set ruleNum=? where sortId=?";
			Object[] param3 ={ruleSort.getRuleNum()+1,ruleSort.getSortId()};
			query.update(conn, sql, param3);
			conn.commit();
			return true;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			try {
				conn.rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			return false;
		}finally{
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	/**
	 * 修改rule
	 * 用事务实现对修改前所属的rulesort的num-1，修改后的所属rulesort的num+1
	 * @param rule
	 * @return boolean
	 */
	@SuppressWarnings({ "deprecation", "unchecked", "rawtypes" })
	public boolean updateRule(Rule rule,int oSortId){
		try {
			String sql = "update t_rule set title=?,link=?,"
					+ "status=?,sortId=?,userId=? where ruleId=?";
			Object[] param = {rule.getTitle(),rule.getLink(),
							   CheckConstant.STATUS_WRITE_DONE,
					           rule.getRuleSort().getSortId(),
					           rule.getUser().getUserId(),
					           rule.getRuleId()};
			conn = DBConnect.getConnect();
			conn.setAutoCommit(false);
			query.update(conn,sql,param);
			sql = "select * from t_rule_sort where sortId=?";
			Object[] param2 = {oSortId};
			ruleSort = (RuleSort)query.query
					   (conn, sql, param2,new BeanHandler(RuleSort.class));
			sql = "update t_rule_sort set ruleNum=? where sortId=?";
			Object[] param3 = {ruleSort.getRuleNum()-1,ruleSort.getSortId()};
			query.update(conn, sql, param3);
			sql = "select * from t_rule_sort where sortId=?";
			Object[] param4 = {rule.getRuleSort().getSortId()};
			ruleSort = (RuleSort)query.query
					(conn, sql,param4,new BeanHandler(RuleSort.class));
			sql = "update t_rule_sort set ruleNum=? where sortId=?";
			Object[] param5 = {ruleSort.getRuleNum()+1,ruleSort.getSortId()};
			query.update(conn, sql, param5);
			conn.commit();
			return true;
		} catch (SQLException e) {
			try {
				conn.rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			return false;
		}finally{
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	/**
	 * 通过ruleid来删除rule
	 * 通过事务实现对该rule所属的rulesort的Num-1
	 * @param rule
	 * @return boolean
	 */
	@SuppressWarnings({ "deprecation", "unchecked", "rawtypes" })
	public boolean deleteRule(Rule rule){
		try {
			String sql = "delete from t_rule where ruleId=?";
			Object[] param = {rule.getRuleId()};
			int sortId = rule.getSortId();
			conn = DBConnect.getConnect();
			conn.setAutoCommit(false);
			query.update(conn, sql, param);
			sql = "select * from t_rule_sort where sortId=?";
			Object[] param2 = {sortId};
			ruleSort = (RuleSort)query.query
					   (conn, sql, param2,new BeanHandler(RuleSort.class));
			sql = "update t_rule_sort set ruleNum=? where sortId=?";
			Object[] param3 = {ruleSort.getRuleNum()-1,ruleSort.getSortId()};
			query.update(conn, sql, param3);
			conn.commit();
			return true;
		} catch (SQLException e) {
			try {
				conn.rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			return false;
		}finally{
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	/**
	 * 通过sortid来删除rule
	 * @param sortId
	 * @return
	 */
	public boolean deleteRuleBySortId(int sortId){
		String sql = "delete from t_rule where sortId=?";
		Object[] params = {sortId};
		int c = update(sql,params);
		if(c>0)
			return true;
		else
			return false;
	}
	/**
	 * 查找所有的rule
	 * @return List<RuleSort>
	 */
	@SuppressWarnings("unchecked")
	public Pager findAllRule(Pager page){
		String sql="select * from t_rule limit ?,? ";
		Object[] param = {(page.getCurrentPage()-1)*page.getPageSize(),page.getPageSize()};
		List<Rule> rule = find(sql,param,Rule.class);
		for(Rule r:rule){
			//把每一个的ruleSort封装到rule里
			r.setRuleSort(ruleSortDao.getRuleSortById(r.getSortId()));
			r.setUser(userDao.getUserById(r.getUserId()));
		}
		page.setList(rule);
		return page;
	}
	/**
	 * 通过rule的id来获得整个rule对象
	 * @return
	 */
	public Rule findRuleById(int ruleId){
		String sql = "select * from t_rule where ruleId=?";
		Object[] params = {ruleId};
		return (Rule)findObject(sql,params,Rule.class);
	}
	/**
	 * 判断数据库中是否有此用户名
	 * @return
	 */
	public boolean ruleName(String ruleName){
		String sql = "select * from t_rule where title=?";
		Object[] param = {ruleName};
		Rule rule = (Rule)findObject(sql, param, Rule.class);
		if(rule==null){
			return false;
		}
		else{
			return true;
		}
	} 
	/**
	 * 得到数据库中rule的行数
	 * @return
	 */
	public int getAllCount(){
		String sql ="select count(*) count from t_rule";
		int c = getCountFromTable(sql, null);
		return c;
	}
}
